package com.atzxh.guigu.netty.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author 小红同学
 * @date 2023-05-08-14:09
 * @description     内容拷贝
 */
public class NIOFileChannel03 {
    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("file01.txt");
        FileChannel fileChannel1 = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("file02.txt");
        FileChannel fileChannel2 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true) {
            // 这个操作很重要，清空buffer
            byteBuffer.clear();
            int read = fileChannel1.read(byteBuffer);
            if (read == -1) { // 表示已读完
                break;
            }
            // 将buffer中数据写入fileChannel2中----02文件
            byteBuffer.flip();
            fileChannel2.write(byteBuffer);
        }

        fileInputStream.close();
        fileOutputStream.close();
    }
}
